package com.tanjun.userservice.web.service.menu.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tanjun.userservice.web.service.menu.entity.BaseAdminRoleMenuEntity;
import com.tanjun.userservice.web.service.menu.mapper.BaseAdminRoleMenuMapper;
import com.tanjun.userservice.web.service.menu.service.BaseAdminMenuService;
import com.tanjun.userservice.web.service.menu.service.BaseAdminRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色和菜单关联表 服务层实现。
 *
 * @author tanjun
 * @since 2025-08-20
 */
@Service
public class BaseAdminRoleMenuServiceImpl extends ServiceImpl<BaseAdminRoleMenuMapper, BaseAdminRoleMenuEntity>  implements BaseAdminRoleMenuService{

    @Autowired
    private BaseAdminMenuService baseAdminMenuService;

    /**
     * 保存角色菜单
     * @param roleId 角色id
     * @param menuIdList 菜单list
     */
    @Override
    public void saveRoleMenus(Long roleId, List<Long> menuIdList) {
        List<BaseAdminRoleMenuEntity> listOld=this.list(QueryChain.of(BaseAdminRoleMenuEntity.class)
                .eq(BaseAdminRoleMenuEntity::getRoleId,roleId)
        );
        //判断需要删除的
        List<BaseAdminRoleMenuEntity> listDel=listOld.stream()
                .filter(t->!menuIdList.contains(t.getMenuId()))
                .toList();
        if(!listDel.isEmpty()){
            this.removeByIds(listDel.stream().map(BaseAdminRoleMenuEntity::getId).toList());
        }
        //插入新的
        List<Long> listOldMenuId=listOld.stream().map(BaseAdminRoleMenuEntity::getMenuId).toList();
        List<Long> listAdd=menuIdList.stream().filter(t->!listOldMenuId.contains(t)).toList();
        if(!listAdd.isEmpty()){
            listAdd.forEach(d->{
                BaseAdminRoleMenuEntity roleMenu=new BaseAdminRoleMenuEntity();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(d);
                this.save(roleMenu);
            });
        }
    }

    /**
     * 删除角色所有的菜单权限
     *
     * @param roleId 角色id
     */
    @Override
    public void delRoleMenus(Long roleId) {
        this.remove(QueryChain.of(BaseAdminRoleMenuEntity.class)
                .eq(BaseAdminRoleMenuEntity::getRoleId,roleId));
    }

    /**
     * 获取角色所有的菜单id
     *
     * @param roleId 角色id
     * @return 返回菜单id list
     */
    @Override
    public List<Long> getRoleMenuIdList(Long roleId) {
        List<BaseAdminRoleMenuEntity> list=this.list(QueryChain.of(BaseAdminRoleMenuEntity.class)
                .select(BaseAdminRoleMenuEntity::getMenuId)
                .eq(BaseAdminRoleMenuEntity::getRoleId,roleId));
        return list.stream().map(BaseAdminRoleMenuEntity::getMenuId).collect(Collectors.toList());
    }


}
